package com.yzh.wanandroid.network.interceptor

import com.yzh.wanandroid.utils.SAVE_USER_LOGIN_KEY
import com.yzh.wanandroid.utils.SAVE_USER_REGISTER_KEY
import com.yzh.wanandroid.utils.SET_COOKIE_KEY
import com.yzh.wanandroid.utils.SpUtils
import okhttp3.Interceptor
import okhttp3.Response

/**
 *   保存 Cookie
 */
class SaveCookieInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        val requestUrl = request.url.toString()
        val host = request.url.host
        if ((requestUrl.contains(SAVE_USER_LOGIN_KEY)
                    || requestUrl.contains(SAVE_USER_REGISTER_KEY))
            && response.headers(SET_COOKIE_KEY).isNotEmpty()
        ) {
            val cookies = response.headers(SET_COOKIE_KEY)
            val cookie = encodeCookie(cookies)
            saveCookie(requestUrl, host, cookie)
        }
        return response
    }

    private fun encodeCookie(cookies: List<String>): String {
        val sb = StringBuilder()
        val set = HashSet<String>()
        cookies.map { cookie ->
            cookie.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        }
            .forEach {
                it.filterNot { set.contains(it) }.forEach { set.add(it) }
            }
        val ite = set.iterator()
        while (ite.hasNext()) {
            val cookie = ite.next()
            sb.append(cookie).append(";")
        }
        val last = sb.lastIndexOf(";")
        if (sb.length - 1 == last) {
            sb.deleteCharAt(last)
        }
        return sb.toString()
    }

    private fun saveCookie(url: String?, host: String?, cookie: String) {
        url ?: return
        SpUtils.putString(url, cookie)
        host ?: return
        SpUtils.putString(host, cookie)
    }
}